import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'umi';
import { Form, Button, Card, Input, InputNumber, Popover, notification } from 'antd';
import EditorForm from '@/components/EditorForm';
import FormCondition from '@/components/FormCondition';
import FlxButton from '@/components/FlxButton'
import { InfoCircleOutlined } from '@ant-design/icons'
import { Row, Col, Tooltip, Space } from 'antd'
import SelectModel from '@/components/SelectModel'
import ShopTable from './components/ShopTable'
import Field from './components/Field';
import FieldModel from './components/FieldModel';
import RuleTemplate from '@/components/RuleTemplate';
import rules1 from './rules1.png'
import rules2 from './rules2.png'
const PlanForm = (props) => {
    const { dispatch, reload } = props;
    const [params, setParams] = useState({
        settleType: 'finish',
        inviteSubFlag: '0',
        joinConditionFlag: '0',
        joinGoods: 'any',
        applyInformationFlag: '0'
    })
    const [data, setData] = useState({})
    const [promoterLevelList, setPromoterLevelList] = useState([])
    const [visible, setVisible] = useState(false);
    const [fields, setFields] = useState([])
    const [fieldsVisible, setFieldVisible] = useState(false)
    const [shopList, setShopList] = useState([])
    const [form] = Form.useForm();
    const promoterRef = useRef(null)
    // 新增修改 传id修改 不传id新增=
    console.log(shopList, 1111111111)
    const fetchRoleEdit = () => {
        form.validateFields().then((values) => {
            const { applyInformationFlag, joinGoods, inviteSubType, validUserList
            } = values
            let validUserCondition = ''
            let validPromoterCondition = ''
            if (applyInformationFlag === '1' && !fields.length) {
                return notification.warning({
                    message: '错误提示',
                    description: '请设置加入条件',
                });
            }
            if (joinGoods === 'only' && !shopList.length) {
                return notification.warning({
                    message: '错误提示',
                    description: '请设置购买指定商品',
                });
            }


            dispatch({
                type: 'promoter/fakeSavePromoterLevel',
                payload: {
                    promoterLevelList: promoterRef.current.fetchData.map((item, index) => {
                        return {
                            ...item,
                            levelIndex: index
                        }
                    })
                }, callback: () => {
                    dispatch({
                        type: 'promoter/fetchPromofakeSavePromoterConfigterWebPage',
                        payload: {
                            ...params,
                            ...values,
                            inviteSubType: inviteSubType ? inviteSubType.toString() : '',
                            applyInformationContent: applyInformationFlag == '1' ? JSON.stringify(fields) : '',
                            joinGoodsIds: joinGoods === 'any' ? 'any' : shopList.map(item => { return item.id }).toString()
                        },
                        callback: () => {
                            reload && reload()
                        }
                    })
                }
            })

        });
    };
    const { settleType, applyInformationFlag, settleDelayDays, inviteSubFlag, joinConditionFlag, joinGoods } = params
    const formItemLayout = {
        labelCol: {
            sm: { span: 0 },
        },
        wrapperCol: {
            sm: { span: 0 },
        },
    };
    const formItems = [
        {
            type: 'noForm',
            formItem: (
                <Space style={{ display: 'flex', alignItems: "center" }}>
                    自动禁用配置: <Form.Item
                        noStyle
                        name={'forbiddenDays'}
                        rules={[
                            {
                                required: false,

                            },
                        ]}
                    >
                        <InputNumber style={{ width: '100%' }} placeholder="请输入天数" />
                    </Form.Item>
                    <div>
                        天内不使用将禁用权限
                    </div>
                </Space>
            ),
        },
        {
            label: '邀请下级',
            name: 'inviteSubFlag',
            type: 'radio',
            onChange: (e) => {
                setParams({
                    ...params,
                    inviteSubFlag: e.target.value,
                    joinConditionFlag: '0',
                    joinGoods: 'any',
                })
            },
            select: {
                0: '关闭',
                1: '开启'
            },
        },
        {
            label: <div style={{ width: 90 }}>下级关联条件</div>,
            name: 'inviteSubType',
            placeholder: '请选择下级关联条件',
            type: 'checkbox',
            visible: inviteSubFlag === '1',
            direction: 'vertical',
            select: {
                withUser: <div>
                    推广员与自己绑定客户关系，自购可获得商品佣金
                    <Popover content={<div>
                        通过“邀请下级”成为推广员，识别到此时无归属推广员，则同时成为邀请人的下级和客户。
                    </div>}>
                        <InfoCircleOutlined></InfoCircleOutlined>
                    </Popover >
                </div>,
                withPromoter: <div>
                    客户申请推广员时，如果是推广员发展的自动成为其下级
                    <Popover content={<div >
                        通过“自主申请”成为推广员，识别到此时有归属推广员，则成为这个推广员的下级。
                    </div>}>
                        <InfoCircleOutlined></InfoCircleOutlined>
                    </Popover >
                </div>
            },

        },
        {
            label: '加入条件',
            name: 'joinConditionFlag',
            visible: inviteSubFlag === '1',
            type: 'radio',
            onChange: (e) => {
                setShopList([])
                setParams({
                    ...params,
                    joinConditionFlag: e.target.value,
                })
            },
            select: {
                0: '无条件',
                1: <Space>
                    有条件<span style={{ color: '#999' }}>满足条件的用户，可申请成为推广员，若关闭申请信息和招募审核，
                        则该用户会自动成为推广员 </span>
                </Space>
            },
        },
        {
            label: '加入条件设置',
            name: 'joinGoods',
            visible: joinConditionFlag === '1' && inviteSubFlag === '1',
            type: 'radio',
            direction: 'vertical',
            onChange: (e) => {
                setParams({
                    ...params,
                    joinGoods: e.target.value
                })
            },
            select: {
                any: '购买店铺任意商品',
                only: '购买指定商品',
            },
        },
        {
            type: 'noForm',
            visible: joinGoods === 'only' && inviteSubFlag === '1',
            formItem: (
                <ShopTable
                    data={shopList}
                    setData={setShopList}
                    onOpen={setVisible}
                >
                </ShopTable>
            ),
        },
        {
            label: '申请信息',
            name: 'applyInformationFlag',
            visible: inviteSubFlag === '1',
            onChange: (e) => {
                setParams({
                    ...params,
                    applyInformationFlag: e.target.value
                })
            },
            type: 'radio',
            select: {
                0: '关闭',
                1: '开启'
            },
        },
        {
            type: 'noForm',
            visible: applyInformationFlag === '1' && inviteSubFlag === '1',
            formItem: (
                <Field
                    data={fields}
                    setData={setFields}
                    onOpen={setFieldVisible}
                >
                    {' '}
                </Field>
            ),
        },
        {
            label: '招募审核',
            name: 'applyCheckFlag',
            visible: inviteSubFlag === '1',
            type: 'radio',
            select: {
                1: '是',
                0: '不是'
            },
        },
        {
            label: <Space>
                <div>结算时间</div>
                <Tooltip title={<div>
                    <div>知识商品：用户支付成功后，即算作交易完成；</div>
                    <div>实物商品：商家发货后，满7天自动确认收货或7天内用户手动确认收货，即算作交易完成。</div>
                </div>}>
                    <InfoCircleOutlined></InfoCircleOutlined>
                </Tooltip>
            </Space>,
            name: 'settleType',
            placeholder: '请选择结算时间',
            type: 'radio',
            direction: 'vertical',
            onChange: (e) => {
                setParams({
                    ...params,
                    settleType: e.target.value,
                    settleDelayDays: 1
                })
            },
            select: {
                finish: <div>交易完成后结算
                    <Tooltip title={<div>
                        <div>交易完成后，立即给推广员发放奖励</div>
                    </div>}>
                        <InfoCircleOutlined></InfoCircleOutlined>
                    </Tooltip>
                </div>,
                delay: <div>
                    <Space>
                        <div>交易完成</div>
                        <InputNumber onChange={(e) => {
                            setParams({
                                ...params,
                                settleDelayDays: e
                            })
                        }} max={90} value={settleDelayDays} disabled={settleType === 'finish'} />
                        <div>天后结算</div>
                    </Space>
                    {settleType === 'delay' && <div style={{
                        color: '#999'
                    }}>2023年4月17日 （GMT+00:00）起提交申请的商户号，交易完成时间为订单结算后7天。</div>}
                </div>,
            },
        },
        {
            label: <Space>
                自购分佣:
            </Space>,
            name: 'selfBuyCommissionType',
            type: 'radio',
            placeholder: '请选择自购分佣',
            direction: 'vertical',
            onChange: (e) => {
                setParams({
                    ...params,
                    selfBuyCommissionType: e.target.value,
                    settleDelayDays: 1
                })
            },
            select: {
                1: <div>
                    推广员与自己绑定客户关系，自购可获得商品佣金
                    <Popover title={<div style={{ width: 400 }}>
                        <img style={{ width: '100%' }} src={rules1} />
                    </div>}>
                        <InfoCircleOutlined></InfoCircleOutlined>
                    </Popover >
                </div>,
                2: <div>
                    推广员不与自己绑定客户关系，自购不可获得商品佣金
                    <Popover title={<div style={{ width: 400 }}>
                        <img style={{ width: '100%' }} src={rules2} />
                    </div>}>
                        <InfoCircleOutlined></InfoCircleOutlined>
                    </Popover >
                </div>,
            },
        },
        {
            label: '考核周期',
            name: 'assessment',
            style: {
                width: 180
            },
            placeholder: '请选择周期考核',
            type: 'select',
            select: [{ name: '月度', value: 'month' }, { name: '季度', value: 'quarter' }, { name: '年度', value: 'year' }]
        }


    ];
    const fetchData = () => {
        dispatch({
            type: 'promoter/fetchPromoterConfigDetail',
            callback: (e) => {
                const { joinGoodsIds, forbiddenDays, assessment, applyInformationFlag, applyInformationContent, joinGoodsList = [], inviteSubFlag, inviteSubType, joinConditionFlag, joinGoods, applyCheckFlag, settleType, selfBuyCommissionType, settleDelayDays, id } = e
                const applyInformationList = applyInformationFlag === '1' ? applyInformationContent ? JSON.parse(applyInformationContent) : [] : []
                const goods = joinGoodsIds === 'any' ? 'any' : joinGoodsIds ? 'only' : 'any'

                setData({
                    applyInformationFlag,
                    inviteSubFlag, inviteSubType, joinConditionFlag, joinGoods, applyCheckFlag, settleType, selfBuyCommissionType, settleDelayDays, id,
                    joinGoods: goods,
                    forbiddenDays: forbiddenDays === 0 ? '' : forbiddenDays,
                    assessment
                })
                setFields(applyInformationList)
                setParams({
                    applyInformationFlag,
                    inviteSubFlag, inviteSubType, joinConditionFlag, joinGoods, applyCheckFlag, settleType, selfBuyCommissionType, settleDelayDays, id,
                    joinGoods: goods,
                    forbiddenDays: forbiddenDays === 0 ? '' : forbiddenDays,
                    assessment
                })
                setShopList(joinGoodsList)
            }
        })
        dispatch({
            type: 'promoter/fetchPromoterLevelDetail',
            callback: (e) => {
                const { promoterLevelList } = e
                setPromoterLevelList(promoterLevelList)
            }
        })
    }

    useEffect(() => {
        fetchData()
    }, [])
    return (
        <div style={{ fontSize: 28 }}>
            <Row>
                <Col span={24}>
                    <div style={{ paddingTop: 12 }}>
                        <FormCondition formItemLayouts={formItemLayout} form={form} formItems={formItems} initialValues={data}></FormCondition>
                    </div>
                    <RuleTemplate ref={promoterRef} promoterLevelList={promoterLevelList}></RuleTemplate>
                </Col>
                <FlxButton onOk={fetchRoleEdit}></FlxButton>
            </Row>
            <SelectModel hasSku={'0'} onOk={(e) => { setShopList(e) }} visible={visible} onClose={() => setVisible(false)}></SelectModel>
            <FieldModel onOk={(e) => {
                setFieldVisible(() => {
                    setFields(e)
                    return false
                });
            }} visible={fieldsVisible} onClose={() => setFieldVisible(false)}></FieldModel>
        </div>
    );
};

export default connect(({ loading }) => ({
    loading: loading.models.institution,
}))(PlanForm);
